package com.pig4cloud.pig.common.feign.handle;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.bblocks.util.ServletUtils;
import com.bblocks.util.TraceIdUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * openfeign 传递：from(自动)，traceId
 */
@Slf4j
//@Configuration
public class FeginInterceptor implements RequestInterceptor {

	@Value("${spring.application.name}")
	private String applicationName;

	@Override
	public void apply(RequestTemplate requestTemplate) {
		try {
			//自动添加本系统的：from：系统名称
			requestTemplate.header(SecurityConstants.FROM, applicationName);
			String traceId = TraceIdUtils.getTraceId(false);
			if(StrUtil.isNotEmpty(traceId))
				requestTemplate.header(TraceIdUtils.TRACE_ID, traceId);//如无就不生成了

			/**
			 * 屏蔽，添加由PigxOAuthRequestInterceptor 负责添加
			Map<String,String> headers = getHeaders();
			for(String headerName : headers.keySet()){
				//只传递部分吧 ACCESS_TOKEN 和FROM 开头的
				if(headerName.toLowerCase().startsWith("access") ) {
					//log.info("添加head：{}=》{}", headerName.toUpperCase(), headers.get(headerName));
					requestTemplate.header(headerName.toUpperCase(), headers.get(headerName));
				}
			}
			 **/
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	private Map<String, String> getHeaders() {

		Map<String, String> map = new LinkedHashMap<>();
		HttpServletRequest request = ServletUtils.getRequest();
		if (request != null){
			Enumeration<String> enumeration = request.getHeaderNames();
			while (enumeration.hasMoreElements()) {
				String key = enumeration.nextElement();
				String value = request.getHeader(key);
				map.put(key, value);
			}
		}
		return map;
	}

}
